from flask import Blueprint, redirect, render_template, request, session, url_for
from module_admin.entity.do.base import db
from module_admin.entity.do.comment import Comment
from module_admin.entity.do.post import Post
from module_admin.utils.http import fail_api, success_api, table_api
from module_admin.utils.validate import str_escape

discussion = Blueprint('Discussion', __name__)


@discussion.route('/discussion', methods=['GET'])
def get_discussion():
    if request.method == 'GET':
        return render_template('Discussion.html')


@discussion.post('/add_post')
def add_post():
    req_json = request.get_json(force=True)
    title = str_escape(req_json.get('title'))
    content = str_escape(req_json.get('content'))
    created_by = str_escape(req_json.get('created_by'))
    user_id = req_json.get('user_id')

    if not title or not content or not user_id:
        return fail_api(msg="标题、内容和用户ID不得为空")

    post = Post(title=title, content=content, created_by=created_by, user_id=user_id)
    db.session.add(post)
    db.session.commit()
    return success_api(msg="帖子发布成功")


@discussion.get('/post_list')
def get_post_list():
    posts = Post.query.all()

    post_list = [
        {
            "id": post.id,
            "title": post.title,
            "content": post.content,
            "created_by": post.created_by,
            "user_id": post.user_id
        }
        for post in posts
    ]

    return table_api(data=post_list, msg="获取帖子列表成功")


@discussion.get('/post/<int:post_id>')
def get_post_with_comments(post_id):
    post = Post.query.filter_by(id=post_id).first()

    if not post:
        return fail_api(msg="帖子不存在")

    # 获取帖子的评论
    comments = Comment.query.filter_by(post_id=post_id).all()
    comment_list = [
        {
            "id": comment.id,
            "post_id": comment.post_id,
            "commenter_type": comment.commenter_type,
            "student_id": comment.student_id,
            "teacher_id": comment.teacher_id,
            "content": comment.content,
            "parent_comment_id": comment.parent_comment_id
        }
        for comment in comments
    ]

    post_data = {
        "id": post.id,
        "title": post.title,
        "content": post.content,
        "created_by": post.created_by,
        "user_id": post.user_id,
        "comments": comment_list
    }

    return table_api(data=post_data, msg="获取帖子及其评论成功")


@discussion.post('/edit_post/<int:post_id>')
def edit_post(post_id):
    req_json = request.get_json(force=True)
    new_title = str_escape(req_json.get('title'))
    new_content = str_escape(req_json.get('content'))

    post = Post.query.filter_by(id=post_id).first()

    if not post:
        return fail_api(msg="帖子不存在")

    if new_title:
        post.title = new_title
    if new_content:
        post.content = new_content

    db.session.commit()
    return success_api(msg="帖子编辑成功")


@discussion.get('/delete_post/<int:post_id>')
def delete_post(post_id):
    post = Post.query.filter_by(id=post_id).first()

    if not post:
        return fail_api(msg="帖子不存在")

    db.session.delete(post)
    db.session.commit()
    return success_api(msg="帖子删除成功")


# @discussion.post('/add_comment')
# def add_comment():
#     req_json = request.get_json(force=True)
#     post_id = req_json.get('post_id')
#     commenter_type = str_escape(req_json.get('commenter_type'))
#     content = str_escape(req_json.get('content'))
#     student_id = req_json.get('student_id')
#     teacher_id = req_json.get('teacher_id')
#     parent_comment_id = req_json.get('parent_comment_id', None)
#
#     if not post_id or not commenter_type or not content:
#         return fail_api(msg="帖子ID、评论者类型和评论内容不得为空")
#
#     comment = Comment(
#         post_id=post_id,
#         commenter_type=commenter_type,
#         student_id=student_id,
#         teacher_id=teacher_id,
#         content=content,
#         parent_comment_id=parent_comment_id
#     )
#     db.session.add(comment)
#     db.session.commit()
#     return success_api(msg="评论发布成功")

# @discussion.post('/add_comment')
# def add_comment():
#     req_json = request.get_json(force=True)
#     commenter_type = str_escape(req_json.get('commenter_type'))
#     content = str_escape(req_json.get('content'))
#     if commenter_type == "teacher":
#         teacher_name = req_json.get('name')
#         comment = Comment(
#             commenter_type=commenter_type,
#             teacher_name=teacher_name,
#             content=content,
#         )
#         db.session.add(comment)
#         db.session.commit()
#         return success_api(msg="评论发布成功")
#     if commenter_type == "student":
#         student_name = req_json.get('name')
#         comment = Comment(
#             commenter_type=commenter_type,
#             student_name=student_name,
#             content=content,
#         )
#         db.session.add(comment)
#         db.session.commit()
#         return success_api(msg="评论发布成功")
#
#
# @discussion.get('/delete_comment/<int:comment_id>')
# def delete_comment(comment_id):
#     comment = Comment.query.filter_by(id=comment_id).first()
#
#     if not comment:
#         return fail_api(msg="评论不存在")
#
#     db.session.delete(comment)
#     db.session.commit()
#     return success_api(msg="评论删除成功1")
#
#
# # GET 接口，获取评论数据
# @discussion.route('/comment/get', methods=['GET'])
# def get_comments():
#     # 获取查询参数
#     post_id = request.args.get('post_id')
#     commenter_type = request.args.get('commenter_type')
#
#     # 查询评论数据，应用筛选条件
#     query = Comment.query
#
#     if post_id:
#         query = query.filter(Comment.post_id == post_id)
#
#     if commenter_type:
#         query = query.filter(Comment.commenter_type == commenter_type)
#
#     # 执行查询
#     comments_list = query.all()
#
#     # 将查询结果转换为字典列表，返回 JSON 响应
#     results = []
#     for comment in comments_list:
#         comment_data = {
#             "id": comment.id,
#             "post_id": comment.post_id,
#             "commenter_type": comment.commenter_type,
#             "student_name": comment.student_name,
#             "teacher_name": comment.teacher_name,
#             "content": comment.content,
#             "parent_comment_id": comment.parent_comment_id,
#             "create_time": comment.create_time.strftime('%Y-%m-%d %H:%M:%S') if comment.create_time else None
#         }
#         results.append(comment_data)
#
#     return table_api(data=results)

@discussion.post('/add_comment')
def add_comment():
    req_json = request.get_json(force=True)
    commenter_type = str_escape(req_json.get('commenter_type'))
    content = str_escape(req_json.get('content'))
    parent_comment_id = req_json.get('parent_comment_id')  # 获取父评论ID

    if commenter_type == "teacher":
        teacher_name = req_json.get('name')
        comment = Comment(
            commenter_type=commenter_type,
            teacher_name=teacher_name,
            content=content,
            parent_comment_id=parent_comment_id  # 设置父评论ID
        )
    elif commenter_type == "student":
        student_name = req_json.get('name')
        comment = Comment(
            commenter_type=commenter_type,
            student_name=student_name,
            content=content,
            parent_comment_id=parent_comment_id  # 设置父评论ID
        )
    else:
        return fail_api(msg="评论者类型无效")

    db.session.add(comment)
    db.session.commit()
    return success_api(msg="评论发布成功")


@discussion.route('/comment/get', methods=['GET'])
def get_comments():
    post_id = request.args.get('post_id')
    commenter_type = request.args.get('commenter_type')
    student_name = request.args.get('student_name')

    query = Comment.query.filter(Comment.parent_comment_id == None)  # 只获取顶层评论（parent_comment_id 为 None）

    if student_name:
        query = query.filter(Comment.student_name == student_name)

    if commenter_type and commenter_type == 'student':  # 如果只查询学生评论
        query = query.filter(Comment.commenter_type == commenter_type)

    # 执行查询，获取顶层评论（学生评论）
    comments_list = query.all()

    # 将查询结果转换为字典列表，返回 JSON 响应
    results = []
    for comment in comments_list:
        comment_data = {
            "id": comment.id,
            "post_id": comment.post_id,
            "commenter_type": comment.commenter_type,
            "student_name": comment.student_name,
            "teacher_name": comment.teacher_name,
            "content": comment.content,
            "parent_comment_id": comment.parent_comment_id,
            "create_time": comment.create_time.strftime('%Y-%m-%d %H:%M:%S') if comment.create_time else None,
            "replies": []  # 初始化子评论列表
        }

        # 查找该学生评论的老师子评论
        replies = Comment.query.filter_by(parent_comment_id=comment.id, commenter_type='teacher').all()
        for reply in replies:
            reply_data = {
                "id": reply.id,
                "commenter_type": reply.commenter_type,
                "teacher_name": reply.teacher_name,
                "content": reply.content,
                "create_time": reply.create_time.strftime('%Y-%m-%d %H:%M:%S') if reply.create_time else None
            }
            comment_data["replies"].append(reply_data)

        results.append(comment_data)

    return table_api(data=results)
